package 剑指Offer.easy;

import java.util.Arrays;
import java.util.Stack;

public class 包含min函数的栈 {
    class MinStack2 {

        int[] array;
        int index = -1;

        private int minValue = Integer.MAX_VALUE;

        /** initialize your data structure here. */
        public MinStack2() {
            array = new int[16];
        }

        public void push(int x) {
            if (index + 1 >= array.length - 1) {
                array = Arrays.copyOf(array, array.length * 2);
            }
            array[++index] = x;
            minValue = x < minValue ? x : minValue;
        }

        public void pop() {
            if (index - 1 < -1) return;
            if (array[index] == minValue) {
                minValue = Integer.MAX_VALUE;
                for (int i = 0; i <= index - 1; i++) {
                    minValue = array[i] < minValue ? array[i] : minValue;
                }
            }
            index--;
        }

        public int top() {
            return array[index];
        }

        public int min() {
            return minValue;
        }
    }

    class MinStack {

        Stack<Integer> stack = new Stack<>();
        Stack<Integer> minStack = new Stack<>();

        /** initialize your data structure here. */
        public MinStack() {
        }

        public void push(int x) {
            stack.push(x);
            if (minStack.isEmpty() || x < minStack.peek()) {
                minStack.push(x);
            } else {
                minStack.push(minStack.peek());
            }
        }

        public void pop() {
            stack.pop();
            minStack.pop();
        }

        public int top() {
            return stack.peek();
        }

        public int min() {
            return minStack.peek();
        }
    }
}
